package com.bird.web.controller.common;

import cn.hutool.core.date.DateUtil;
import com.bird.common.utils.ServletUtil;
import com.bird.framework.domain.Result;
import com.bird.framework.domain.page.PageDomain;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author bird
 */
public class BaseController {

	/**
	 * 将前台传递过来的日期格式的字符串，自动转化为Date类型
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtil.parseDate(text));
			}
		});

	}

	/**
	 * 设置请求分页数据
	 */
	protected void startPage() {
		PageDomain.startPage();
	}

	protected Result ok() {
		return Result.ok();
	}

	protected Result ok(String msg) {
		return Result.ok(msg, null);
	}

	protected <T> Result<T> ok(Object t) {
		return Result.ok(t);
	}

	protected <T> Result<T> ok(String msg, T t) {
		return Result.ok(msg, t);
	}

	protected Result no() {
		return Result.no();
	}

	protected Result no(String msg) {
		return Result.no(msg);
	}

	protected <T> Result<T> no(T t) {
		return Result.no(t);
	}

	protected <T> Result<T> no(String msg, T t) {
		return Result.no(msg, t);
	}

	protected <T> Result<PageInfo<T>> page(PageInfo<T> page) {
		return Result.ok(page);
	}

	protected <T> Result<PageInfo<T>> page(List<T> page) {
		return Result.ok(new PageInfo<T>(page));
	}

	/**
	 * 页面跳转
	 */
	public String redirect(String url) {
		return String.format("redirect:%s", url);
	}

	/**
	 * 导出excel
	 *
	 * @param workbook
	 * @param fileName
	 */
	protected void export(Workbook workbook, String fileName) {
		ServletUtil.exportExcel(workbook, fileName);
	}

}
